<template>
  <div class="common-layout">
    <span style="font-size:30px">题库生成</span>
    <el-divider />
    
    <el-card class="content-box">
      <template #header>
        <div class="card-header">
          <span style="font-size: 20px;">题库内容预览</span>
        </div>
      </template>

      <el-scrollbar max-height="600px">
        <el-table :data="tableData" style="width: 100%" height="600" border>
          <!-- 题型列，增加映射展示中文 -->
          <el-table-column prop="type" label="题型" width="120">
            <template #default="scope">
              {{ typeMapping(scope.row.type) }}
            </template>
          </el-table-column>

          <!-- 题干 -->
          <el-table-column prop="question" label="题干" />

          <!-- 选项 -->
          <el-table-column prop="options" label="选项">
            <template #default="scope">
              <div v-if="scope.row.options && scope.row.options.length">
                <div v-for="(opt, idx) in scope.row.options" :key="idx">
                  {{ optionLetter(idx) }}: {{ opt.optionName }}
                </div>
              </div>
              <div v-else>—</div>
            </template>
          </el-table-column>

          <!-- 正确答案 -->
          <el-table-column prop="correctAnswer" label="正确答案">
            <template #default="scope">
              <div>
                <span v-if="Array.isArray(scope.row.correctAnswer)">
                  {{ scope.row.correctAnswer.join(', ') }}
                </span>
                <span v-else>{{ scope.row.correctAnswer }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-card>

    <!-- 导出按钮 -->
    <el-row justify="center" class="button-row">
      <el-col :span="6" class="button-wrapper">
        <el-button type="primary" @click="exportTxt">
          导出 TXT
          <el-icon class="el-icon--right">
            <Upload />
          </el-icon>
        </el-button>
      </el-col>

      <el-col :span="6" class="button-wrapper">
        <el-button type="success" @click="exportDocx">
          导出 DOCX
          <el-icon class="el-icon--right">
            <Upload />
          </el-icon>
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { saveAs } from 'file-saver';
import { Packer, Document, Paragraph, TextRun } from 'docx';

const props = defineProps({
  content: {
    type: Array,
    default: () => []
  }
});

const tableData = ref([]);

// 题型映射函数
const typeMapping = (type) => {
  const mapping = {
    singleChoice: '单选题',
    multipleChoice: '多选题',
    trueOrFalse: '判断题',
    shortAnswer: '简答题'
  };
  return mapping[type] || type;
};

// 将 0->A, 1->B, ...
const optionLetter = (index) => String.fromCharCode(65 + index);

watch(
  () => props.content,
  (val) => {
    if (Array.isArray(val)) {
      tableData.value = val;
    }
  },
  { immediate: true }
);

// 导出 TXT 文件
const exportTxt = () => {
  const content = tableData.value.map(item => {
    const type = typeMapping(item.type);
    const question = item.question;
    const options = item.options ? item.options.map((opt, idx) => `${optionLetter(idx)}: ${opt.optionName}`).join('\n') : '—';
    const correctAnswer = Array.isArray(item.correctAnswer) ? item.correctAnswer.join(', ') : item.correctAnswer;

    return `${type}:\n${question}\n选项:\n${options}\n正确答案: ${correctAnswer}\n\n`;
  }).join('\n');

  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
  saveAs(blob, '题库.txt');
};

// 导出 DOCX 文件
const exportDocx = () => {
  const doc = new Document({
    sections: [{
      properties: {},
      children: tableData.value.map((item, idx) => {
        const children = [
          new Paragraph({
            children: [
              new TextRun({
                text: `第 ${idx + 1} 题【${typeMapping(item.type)}】`,
                bold: true,
                size: 28
              }),
            ]
          }),
          new Paragraph({
            children: [
              new TextRun(item.question),
            ]
          }),
        ];

        if (item.options && item.options.length) {
          item.options.forEach((opt, optIdx) => {
            children.push(new Paragraph(`${optionLetter(optIdx)}. ${opt.optionName}`));
          });
        }

        children.push(new Paragraph(`【答案】：${Array.isArray(item.correctAnswer) ? item.correctAnswer.join(', ') : item.correctAnswer}`));
        children.push(new Paragraph(''));

        return children;
      }).flat()
    }]
  });

  Packer.toBlob(doc).then(blob => {
    saveAs(blob, "题库.docx");
  });
};
</script>

<style scoped>
.content-box {
  margin-top: 20px;
  background: #f6f8fa;
  padding: 10px;
  border-radius: 6px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  word-break: break-word;
  border: 1px solid #dcdfe6;
  max-height: 750px;
  overflow: hidden;
  width:80%;
}


.el-card {
  max-height: 800px;
}

.button-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
}

.button-row {
  margin-top: 20px;
}
</style>
